Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

254
Visualizações
"Uncaught SyntaxError: Unexpected token l in JSON at position 0", but still works, why?

First time using websockets with Go and getting a weird error that doesn't break the program, and still continue as if it was not a problem. The client is a ReactJS single page application.

JS Client:

 const socket = new WebSocket("ws://localhost:5000/ws");
            setConnection(socket);

            socket.onmessage = (e) => {
                const message = JSON.parse(e.data)
                console.log("message:", message)
          
                switch (message.Command) {
                  case "loginResult":
                    if (message.Result) {
                      console.log("login worked");
                    }else{
                      console.log("login did not work");
                    }
                    break;
                }
              }

Snippet of Go it is getting JSON from:

result := ws.LoginResult{
        BaseMessage: ws.BaseMessage{
            Command: "loginResult",
        },
        Result: false,
    }

b, err := json.Marshal(result)

if err != nil {
    fmt.Println(err)
    return
}

if err = conn.WriteMessage(msgType, b); err != nil {
    return
}

And the output:

in here
WebsocketProvider.tsx:20 message: {Command: 'loginResult', Result: false}
WebsocketProvider.tsx:27 login did not work
VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (<anonymous>)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

Anyone have any idea why this is the case?

Solution was found:

  • It was to do with the migration of code and that a left over line was making a call that was ignored, hence where it made no difference to the execution. Nothing to do with the JSON format being difference since this was automatically generate by Go libraries.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

the function you have written for onmessage will be run every time a valid websocket message has been received.

According to the debug log you have posted the bit that worked was when you did receive valid JSON from the server and the function ran to completion as evidenced by this line:

WebsocketProvider.tsx:27 login did not work

Mark the line number.

After this you get:

VM3502:1 Uncaught SyntaxError: Unexpected token l in JSON at position 0
    at JSON.parse (<anonymous>)
    at WebSocket.socket.onmessage (WebsocketProvider.tsx:19)
socket.onmessage @ WebsocketProvider.tsx:19

mark the line number :19 This is the line with your JSON.parse.

My guess would be that this is a new invalid json message and it did indeed panic here and the rest of the function did not run - the bit that ran was a previous message with valid json.

As for why it failed - put in a console.log before your JSON.parse as suggested by @emptyhua to see what exactly you are receiving.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda